package com.m.crm.service.impl;

import com.m.crm.cache.RedisCache;
import com.m.crm.dao.AccountDao;
import com.m.crm.entity.Account;
import com.m.crm.enums.ResultEnum;
import com.m.crm.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by yugoh on 2017/5/24.
 */
@Service
public class AccountServiceImpl implements AccountService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private final RedisCache cache;
    private final AccountDao accountDao;

    @Autowired
    public AccountServiceImpl(RedisCache cache, AccountDao accountDao) {
        this.cache = cache;
        this.accountDao = accountDao;
    }

    @Transactional
    @Override
    public Account register(Account account, String securityCode) {
        String cacheKey = RedisCache.CAHCENAME + "|securityCode|" + account.getEmail();
        if (!(securityCode != null && securityCode.equals(cache.getCache(cacheKey, String.class)))) {
            throw new RuntimeException(ResultEnum.SECURITY_CODE_IS_ILLICIT.getMsg());
        }
        cache.deleteCache(cacheKey);
        account.setState("0");
        if (accountDao.saveAccount(account) != 1 && account.getId() == null) {
            throw new RuntimeException(ResultEnum.DB_INSERT_RESULT_ERROR.getMsg());
        }
        return account;
    }

    @Override
    public List<Account> listAccount(Account account, Date startTime, Date endTime, Integer offset, Integer limit) {
        return accountDao.listAccount(account, offset, limit, startTime, endTime);
    }

    @Override
    public Account getAccountByTag(Integer accountId, String email, String idCard) {
        return accountDao.getAccountByTag(accountId, email, idCard);
    }
}
